﻿using Basic.FlowCollect;
using Basic.FlowLocalEvent.Model;
using Basic.FlowModel.Node;
using Basic.FlowRemoteModel;
using WeDonekRpc.Client.Attr;
using WeDonekRpc.Client.Interface;
using WeDonekRpc.Helper;

namespace Basic.FlowLocalEvent.FlowNode
{
    [LocalEventName("Update", "Delete")]
    internal class RefreshNode : IEventHandler<FlowNodeEvent>
    {
        private readonly IFlowNodeCollect _Node;
        private readonly IFlowCollect _Flow;
        public RefreshNode ( IFlowNodeCollect node, IFlowCollect flow )
        {
            this._Node = node;
            this._Flow = flow;
        }

        public void HandleEvent ( FlowNodeEvent data, string eventName )
        {
            if ( data.Node.NodeType == FlowNodeType.结束节点 )
            {
                return;
            }
            ToNoteBase[] nodes = this._Node.GetsToNode(data.Node.Id);
            if ( !nodes.IsNull() && nodes.IsExists(c => c.IntoFormula.IsNull() == false) )
            {
                long? formId = data.Node.FormId;
                if ( !formId.HasValue )
                {
                    formId = this._Flow.GetDefFormId(data.Node.FlowId);
                    if ( formId.HasValue == false )
                    {
                        return;
                    }
                }
                ToNoteBase[] sets = nodes.FindAll(a =>
                {
                    bool isSet = false;
                    if ( !a.IntoFormula.IsNull() )
                    {
                        int index = a.IntoFormula.FindIndex(c => c.NodeId == a.Id && c.FormId != formId.Value);
                        if ( index != -1 )
                        {
                            a.IntoFormula = a.IntoFormula.Remove(index);
                            isSet = true;
                        }
                    }
                    if ( eventName == "Delete" )
                    {
                        if ( a.BackNodeId.HasValue && a.BackNodeId.Value == data.Node.Id )
                        {
                            a.BackNodeId = null;
                            isSet = true;
                        }
                        if ( a.OutWaitNodeId.HasValue && a.OutWaitNodeId.Value == data.Node.Id )
                        {
                            a.OutWaitNodeId = null;
                            isSet = true;
                        }
                    }
                    return isSet;
                });
                if ( sets.Length > 0 )
                {
                    this._Node.Set(sets);
                }
            }
        }
    }
}
